//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖保佑             永无BUG 
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//                  不见满街漂亮妹，哪个归得程序员？  


/* ****************************************************************************
 * Author:      671643387
 * Date:        2015/11/30
 * Description: 星座奇缘
 * ***************************************************************************/

function parseDate(strDate) {
    // 2013:8:7:14:0:0
    if (typeof(strDate) != 'string') {
        return 0;
    }

    var segs = strDate.split(':');
    if (6 == segs.length) {
        // 获取活动开始和结束的时间(秒)
        var date = new Date(segs[0], +segs[1] - 1, segs[2], segs[3], segs[4], segs[5]);
        return Math.floor(date.getTime() / 1000);
    } else {
        ERROR('parseDate invalid date:' + strDate);
    }

    return 0;
}

/**
 * 判断是否在糖果活动时间
 * @param delay
 * @returns {*}
 */
function in_candy(delay) {
    var startTime = parseDate(gConfGlobal.XingzuoRomanceCandyStartTime);
    var endTime = parseDate(gConfGlobal.XingzuoRomanceCandyEndTime);

    if (delay) {
        endTime += 86400;
    }

    var now = common.getTime();

    return ( ( now >= startTime ) && ( now <= endTime ) );
}

function random_star(conf, pos, nor)
{
    var random_map = {};
    var randos_pos = pos;
    var total_prob = 0;

    var item = conf[randos_pos];
    while(item)
    {
        var item_prob = 0;
        if (in_candy()) {
            // 糖果概率
            item_prob = +(nor ? item['CandyNormal'] : item['CandyHigh']);
        } else {
            item_prob = +(nor ? item['Normal'] : item['High']);
        }
        if (item_prob > 0) {
            total_prob += item_prob;
            random_map[total_prob] = randos_pos;
        }
        item = conf[++randos_pos];
    }

    randos_pos = 1;
    while (randos_pos < pos)
    {
        item = conf[randos_pos];
        var item_prob = 0;
        if (in_candy()) {
            // 糖果概率
            item_prob = +(nor ? item['CandyNormal'] : item['CandyHigh']);
        } else {
            item_prob = +(nor ? item['Normal'] : item['High']);
        }
        if (item_prob > 0) {
            total_prob += item_prob;
            random_map[total_prob] = randos_pos;
        }
        item = conf[++randos_pos];
    }

    var random_prob = Math.floor(Math.random() * total_prob);

    for (var _key in random_map) {
        if (random_prob < +_key) {
            return +random_map[_key];
        }
    }

    return 1;
}

exports.normal = function(player, req, resp, onHandled) {
    do {

        if (player.user.status.level < +gConfGlobal.HoroscopeOpenLevel) {
            resp.code = 1; resp.desc = 'level not reach'; break;
        }

        var xzr = player.user.xingzuo_romance;

        if (!gConfSwitch.xingzuoRomance) {
            resp.code = 1; resp.desc = 'not open'; break;
        }

        // 判断当日普通占星次数是否已经用完
        if (xzr.normal >= +gConfGlobal.XingzuoRomanceNormal) {
            resp.code = 1; resp.desc = 'normal used up'; break;
        }

        // 随机
        var random_pos = random_star(gConfXingzuoRomance, xzr.pos, true);

        // 修改数据
        xzr.pos = random_pos;
        ++xzr.normal;

        // 添加奖励
        if (in_candy()) {
            // 糖果积分
            var candy = +gConfXingzuoRomance[random_pos].Candy;
            xzr.candy = (+xzr.candy || 0);
            xzr.candy += candy;
            resp.data.candy = candy;
        } else {
            var point = +gConfXingzuoRomance[random_pos].Point;
            if (point > 0) {
                xzr.point += point;
                resp.data.point = point;
            } else {
                resp.data.awards = player.addAwards(gConfXingzuoRomance[random_pos].Awards);
            }
        }
        player.markDirty("xingzuo_romance");
        resp.data.pos = random_pos;
    } while (false);

    onHandled && onHandled();
};

exports.high = function(player, req, resp, onHandled) {
    do {
        if (player.user.status.level < +gConfGlobal.HoroscopeOpenLevel) {
            resp.code = 1; resp.desc = 'level not reach'; break;
        }

        var xzr = player.user.xingzuo_romance;

        if (!gConfSwitch.xingzuoRomance) {
            resp.code = 1; resp.desc = 'not open'; break;
        }

        // 扣除玩家元宝
        var confBuy = gConfBuy[xzr.high + 1];
        if( !confBuy ) {
            resp.code = 1; resp.desc = 'no more to buy'; break;
        }
        var costCash = +confBuy.CashXingzuoRomance;
        if( !costCash ) {
            resp.code = 1; resp.desc = 'no more to buy'; break;
        }
        if (!player.costResource("cash", costCash)) {
            resp.code = 1; resp.desc = 'you need more cash'; break;
        }

        // 随机
        var random_pos = random_star(gConfXingzuoRomance, xzr.pos, false);

        // 修改数据
        xzr.pos = random_pos;
        ++xzr.high;

        // 添加奖励
        if (in_candy()) {
            // 糖果积分
            var candy = +gConfXingzuoRomance[random_pos].Candy;
            xzr.candy = (+xzr.candy || 0);
            xzr.candy += candy;
            resp.data.candy = candy;
        } else {
            var point = +gConfXingzuoRomance[random_pos].Point;
            if (point > 0) {
                xzr.point += point;
                resp.data.point = point;
            } else {
                resp.data.awards = player.addAwards(gConfXingzuoRomance[random_pos].Awards);
            }
        }
        player.markDirty("xingzuo_romance");
        resp.data.pos = random_pos;
        resp.data.cash = -costCash;

    } while (false);

    onHandled && onHandled();
};

exports.buy = function(player, req, resp, onHandled) {
    do {
        if (player.user.status.level < +gConfGlobal.HoroscopeOpenLevel) {
            resp.code = 1; resp.desc = 'level not reach'; break;
        }

        var xzr = player.user.xingzuo_romance;

        if (!gConfSwitch.xingzuoRomance) {
            resp.code = 1; resp.desc = 'not open'; break;
        }

        var id = parseInt(req.args.id);
        var num = parseInt(req.args.num);
        if (num < 1 || num > 999) {
            resp.code = 1; resp.desc = 'invalid num'; break;
        }

        var conf = gConfXingzuoRomanceShop[id];
        if (!conf) {
            resp.code = 1; resp.desc = 'invalid id'; break;
        }

        var needPoint = conf.Price * num;
        if (xzr.point < needPoint) {
            resp.code = 1; resp.desc = 'lack of point'; break;
        }

        // 扣除玩家积分
        xzr.point -= needPoint;
        player.markDirty("xingzuo_romance.point");

        // 添加道具
        var awards = [];
        var award = conf.Award;
        if (num > 1) {
            award = clone(award);
            award[2] *= num;
        }
        awards.push(award);
        resp.data.awards = player.addAwards(awards);
        resp.data.point = -needPoint;
    } while (false);
    onHandled && onHandled();
};

exports.buy_candy = function(player, req, resp, onHandled) {
    do {
        if (!in_candy(true)) {
            resp.code = 1; resp.desc = 'candy shop closed'; break;
        }

        if (player.user.status.level < +gConfGlobal.HoroscopeOpenLevel) {
            resp.code = 1; resp.desc = 'level not reach'; break;
        }

        var xzr = player.user.xingzuo_romance;

        if (!gConfSwitch.xingzuoRomance) {
            resp.code = 1; resp.desc = 'not open'; break;
        }

        var id = parseInt(req.args.id);
        var num = parseInt(req.args.num);
        if (num < 1 || num > 999) {
            resp.code = 1; resp.desc = 'invalid num'; break;
        }

        var conf = gConfXingzuoRomanceShop[id];
        if (!conf) {
            resp.code = 1; resp.desc = 'invalid id'; break;
        }

        var needCandy = conf.PriceCandy * num;
        if (xzr.candy < needCandy) {
            resp.code = 1; resp.desc = 'lack of candy'; break;
        }

        // 扣除玩家糖果
        xzr.candy -= needCandy;
        player.markDirty("xingzuo_romance.candy");

        // 添加道具
        var awards = [];
        var award = conf.AwardCandy;
        if (num > 1) {
            award = clone(award);
            award[2] *= num;
        }
        awards.push(award);
        resp.data.awards = player.addAwards(awards);
        resp.data.candy = -needCandy;
    } while (false);
    onHandled && onHandled();
};